package cc.yiueil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@WebServlet(urlPatterns = "/api-test")
public class ApiTestServlet extends HttpServlet {
    /**
     * 请求: http://localhost:8080/02-servlet/api-test?name=zhangsan&pass=123456
     * getMethod()：返回请求方法，例如，`"GET"`，`"POST"`；
     * getRequestURI()：返回请求路径，但不包括请求参数，例如，`"/hello"`；
     * getQueryString()：返回请求参数，例如，`"name=Bob&a=1&b=2"`；
     * getParameter(name)：返回请求参数，GET请求从URL读取参数，POST请求从Body中读取参数；
     * getContentType()：获取请求Body的类型，例如，`"application/x-www-form-urlencoded"`；
     * getContextPath()：获取当前Webapp挂载的路径，对于ROOT来说，总是返回空字符串`""`；
     * getCookies()：返回请求携带的所有Cookie；
     * getHeader(name)：获取指定的Header，对Header名称不区分大小写；
     * getHeaderNames()：返回所有Header名称；
     * getInputStream()：如果该请求带有HTTP Body，该方法将打开一个输入流用于读取Body；
     * getReader()：和getInputStream()类似，但打开的是Reader；
     * getRemoteAddr()：返回客户端的IP地址；
     * getScheme()：返回协议类型，例如，`"http"`，`"https"`；
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("req.getScheme() = " + req.getScheme());
        System.out.println("req.getMethod() = " + req.getMethod());
        System.out.println("req.getRequestURI() = " + req.getRequestURI());
        System.out.println("req.getQueryString() = " + req.getQueryString());
        System.out.println("req.getParameterMap() = " + req.getParameterMap());
        System.out.println("req.getParameterNames() = " + req.getParameterNames());
        System.out.println("req.getContentType() = " + req.getContentType());
        System.out.println("req.getContextPath() = " + req.getContextPath());
        System.out.println("req.getCookies() = " + Arrays.toString(req.getCookies()));
        System.out.println("req.getHeaderNames() = " + req.getHeaderNames());

        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("my-header", "yiueil");
        Cookie cookie = new Cookie("my-cookie", "yiueil");
        cookie.setDomain("localhost");
        cookie.setMaxAge(60);
        resp.addCookie(cookie);
    }
}
